<template>
  <div class="app-container">
    <div class="fixed-header">
      <el-alert
          title="提示：请选择左侧的菜单树节点分配权限。"
          type="warning"
          :closable="false"
          show-icon>
      </el-alert>
      <el-row :gutter="20">
        <el-col :span="6" :xs="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>角色信息</span>
              </div>
            </template>
            <div>
              <div class="role-info">
                <span class="role-name">角色名称：{{ role.roleName }}</span>
                <div class="role-key">角色编码：{{ role.roleCode }}</div>
                <div class="role-description">{{ role.description }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="18" :xs="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>菜单权限分配</span>
                <div class="button-group">
                  <el-button type="primary" :loading="loading" @click="submitForm">保存</el-button>
                  <el-button @click="goBack">返回</el-button>
                </div>
              </div>
            </template>
            <el-tree
                :data="menuOptions"
                show-checkbox
                ref="menuTreeRef"
                node-key="id"
                empty-text="加载中，请稍候"
                :props="defaultProps"
                :check-strictly="false"
                lazy
                :load="loadNode"
            ></el-tree>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {getRole} from "@/api/role";
import request from "@/utils/request";
import {listChildMenu, listRootMenu} from "@/api/menu";

export default {
  name: "RoleAuth",
  data() {
    return {
      // 角色ID
      roleId: null,
      // 角色信息
      role: {},
      // 菜单树选项
      menuOptions: [],
      // 菜单树配置
      defaultProps: {
        children: "children",
        label: "menuName",
        isLeaf: "isLeaf"
      },
      // 加载状态
      loading: false,
      // 角色已选菜单ID
      checkedMenuIds: []
    };
  },
  created() {
    const roleId = this.$route.params.roleId;
    this.roleId = roleId;
    this.getRoleInfo(roleId);
    this.getCheckedMenus(roleId);
    this.loadRootMenu();
  },
  methods: {
    // 获取角色信息
    getRoleInfo(roleId) {
      getRole(roleId).then(response => {
        this.role = response.data;
      });
    },
    // 加载根菜单
    loadRootMenu() {
      this.loading = true;
      listRootMenu().then(res => {
        this.menuOptions = res.data.map(item => {
          // 根据菜单类型判断是否为叶子节点
          return {
            ...item,
            isLeaf: item.menuType === 'F' // 如果是按钮类型，则为叶子节点
          };
        });
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 懒加载节点
    loadNode(node, resolve) {
      // 如果是根节点，已在created中加载
      if (node.level === 0) {
        return resolve([]);
      }

      const parentId = node.data.id;
      listChildMenu(parentId).then(res => {
        // 处理子节点数据
        const childNodes = res.data.map(item => {
          return {
            ...item,
            isLeaf: item.menuType === 'F' // 如果是按钮类型，则为叶子节点
          };
        });

        // 设置子节点已选状态
        this.$nextTick(() => {
          if (this.checkedMenuIds && this.checkedMenuIds.length > 0) {
            childNodes.forEach(item => {
              if (this.checkedMenuIds.includes(item.id)) {
                this.$refs.menuTreeRef.setChecked(item.id, true, false);
              }
            });
          }
        });

        resolve(childNodes);
      }).catch(() => {
        resolve([]);
      });
    },
    // 获取角色已分配的菜单ID
    getCheckedMenus(roleId) {
      request({
        url: '/api/system/role-menu/menuIds/' + roleId,
        method: 'get'
      }).then(res => {
        this.checkedMenuIds = res.data;
        // 对已加载的节点设置选中状态
        this.$nextTick(() => {
          if (this.$refs.menuTreeRef && this.checkedMenuIds && this.checkedMenuIds.length > 0) {
            this.checkedMenuIds.forEach(menuId => {
              this.$refs.menuTreeRef.setChecked(menuId, true, false);
            });
          }
        });
      });
    },
    // 提交授权
    submitForm() {
      if (this.roleId) {
        this.loading = true;
        const roleMenuForm = {
          id: this.roleId,
          menuIds: this.$refs.menuTreeRef.getCheckedKeys()
        };
        request({
          url: '/api/system/role-menu',
          method: 'put',
          data: roleMenuForm
        }).then(res => {
          this.$message.success("授权成功");
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    },
    // 返回
    goBack() {
      this.$router.push('/role');
    }
  }
};
</script>

<style scoped>
.fixed-header {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.role-info {
  padding: 10px 0;
}

.role-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  display: block;
}

.role-key {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.role-description {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}
</style>
